package com.hwz.task;

import com.hwz.constant.MessageConstant;
import com.hwz.entity.Orders;
import com.hwz.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * [一句话描述该类的功能]
 *
 * @author : [Lenovo]
 * @version : [v1.0]
 * @createTime : [2024/3/30 15:06]
 */
@Slf4j

@Component
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理长时间未支付订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("处理支付超时订单：{}", new Date());
        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT,localDateTime);
        if (ordersList != null && ordersList.size() > 0)
        {
            for (Orders orders:ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单长时间没支付，自动取消");
                orderMapper.update(orders);
            }
        }

    }

    /**
     * 处理“派送中”状态的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中订单：{}", new Date());
        LocalDateTime localDateTime = LocalDateTime.now().minusHours(1);
        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, localDateTime);
        if (ordersList != null && ordersList.size() > 0)
        {
            for (Orders orders:ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
